/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>Project: javaseapp - Ex7
 * <p>Powered by webrx On 2021-08-25 17:30:51
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Ex7 {
    //true代表 公平锁
    //static Lock lock = new ReentrantLock(true);
    static Lock lock = new ReentrantLock();

    public static void m1() {
        for (int i = 0; i < 3; i++) {
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String t = Thread.currentThread().getName();
            System.out.printf("%s 执行完成%n", t);
            lock.unlock();
        }

    }

    public static void m2() {
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String t = Thread.currentThread().getName();
        System.out.printf("%s 执行完成%n", t);
        lock.unlock();

    }

    public static void m3() {
        lock.lock();
        String t = Thread.currentThread().getName();
        System.out.printf("%s 执行完成%n", t);
        lock.unlock();
    }

    public static void m4() {
        try {
            lock.lockInterruptibly();
            System.out.println("线程T2终于打断了");
        } catch (InterruptedException e) {
            System.out.println("....");
        } finally {
            if (lock.tryLock())
                lock.unlock();
            lock = new ReentrantLock();
            System.out.println("线程T4结束了");
            //System.exit(0);
        }
    }

    public static void main(String[] args) {
        //测试重入锁打断
        new Thread(Ex7::m2, "T2").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //new Thread(Ex7::m3, "T3").start();

        var t4 = new Thread(Ex7::m4, "T4");
        t4.start();
        t4.interrupt();//打断编程锁
        System.out.println(Thread.activeCount());

    }

    public static void one(String[] args) {
        new Thread(Ex7::m1, "T1").start();
        new Thread(Ex7::m1, "T2").start();
        new Thread(Ex7::m1, "T3").start();
        
    }


}
